// Manager Script - 管理所有录制

class RecordingManager {
  constructor() {
    this.recordings = [];
    this.filteredRecordings = [];
    this.deleteTargetId = null;
    
    // DOM元素
    this.elements = {
      recordingsGrid: document.getElementById('recordingsGrid'),
      searchInput: document.getElementById('searchInput'),
      sortSelect: document.getElementById('sortSelect'),
      deleteModal: document.getElementById('deleteModal'),
      cancelDeleteBtn: document.getElementById('cancelDeleteBtn'),
      confirmDeleteBtn: document.getElementById('confirmDeleteBtn')
    };
    
    this.init();
  }
  
  async init() {
    // 加载录制数据
    await this.loadRecordings();
    
    // 设置事件监听器
    this.setupEventListeners();
  }
  
  async loadRecordings() {
    try {
      const response = await chrome.runtime.sendMessage({
        action: 'GET_RECORDINGS'
      });
      
      if (response.success) {
        this.recordings = response.recordings;
        this.filteredRecordings = [...this.recordings];
        this.sortRecordings();
        this.renderRecordings();
      }
    } catch (error) {
      console.error('Failed to load recordings:', error);
      this.showError();
    }
  }
  
  setupEventListeners() {
    // 搜索
    this.elements.searchInput.addEventListener('input', (e) => {
      this.filterRecordings(e.target.value);
    });
    
    // 排序
    this.elements.sortSelect.addEventListener('change', () => {
      this.sortRecordings();
      this.renderRecordings();
    });
    
    // 删除模态框
    this.elements.cancelDeleteBtn.addEventListener('click', () => {
      this.hideDeleteModal();
    });
    
    this.elements.confirmDeleteBtn.addEventListener('click', () => {
      this.confirmDelete();
    });
    
    // 点击外部关闭菜单
    document.addEventListener('click', (e) => {
      if (!e.target.closest('.recording-menu')) {
        document.querySelectorAll('.menu-dropdown').forEach(menu => {
          menu.classList.remove('show');
        });
      }
    });
  }
  
  filterRecordings(searchTerm) {
    const term = searchTerm.toLowerCase().trim();
    
    if (!term) {
      this.filteredRecordings = [...this.recordings];
    } else {
      this.filteredRecordings = this.recordings.filter(recording => {
        return recording.title.toLowerCase().includes(term) ||
               recording.url?.toLowerCase().includes(term) ||
               recording.steps.some(step => 
                 step.description.toLowerCase().includes(term)
               );
      });
    }
    
    this.sortRecordings();
    this.renderRecordings();
  }
  
  sortRecordings() {
    const sortValue = this.elements.sortSelect.value;
    
    this.filteredRecordings.sort((a, b) => {
      switch (sortValue) {
        case 'date-desc':
          return new Date(b.startTime) - new Date(a.startTime);
        case 'date-asc':
          return new Date(a.startTime) - new Date(b.startTime);
        case 'name-asc':
          return a.title.localeCompare(b.title);
        case 'name-desc':
          return b.title.localeCompare(a.title);
        case 'steps-desc':
          return b.steps.length - a.steps.length;
        case 'steps-asc':
          return a.steps.length - b.steps.length;
        default:
          return 0;
      }
    });
  }
  
  renderRecordings() {
    if (this.filteredRecordings.length === 0) {
      this.elements.recordingsGrid.innerHTML = `
        <div class="empty-state">
          <svg width="80" height="80" viewBox="0 0 80 80" fill="none">
            <rect x="16" y="16" width="48" height="48" rx="4" stroke="currentColor" stroke-width="2" stroke-dasharray="4 4"/>
            <path d="M32 40h16M40 32v16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
          <h2>No recordings found</h2>
          <p>${this.recordings.length === 0 ? 'Start recording to create your first guide' : 'Try adjusting your search terms'}</p>
          ${this.recordings.length === 0 ? '<a href="#" class="btn btn-primary" id="createFirstBtn">Create First Recording</a>' : ''}
        </div>
      `;
      
      // 绑定创建第一个录制的按钮
      const createBtn = document.getElementById('createFirstBtn');
      if (createBtn) {
        createBtn.addEventListener('click', (e) => {
          e.preventDefault();
          window.close();
        });
      }
      
      return;
    }
    
    this.elements.recordingsGrid.innerHTML = this.filteredRecordings.map(recording => `
      <div class="recording-card" data-id="${recording.id}">
        <div class="recording-header">
          <div>
            <h3 class="recording-title">${this.escapeHtml(recording.title)}</h3>
            ${recording.url ? `<a href="${recording.url}" class="recording-url" target="_blank" onclick="event.stopPropagation()">${recording.url}</a>` : ''}
          </div>
          <div class="recording-menu">
            <button class="menu-btn" onclick="event.stopPropagation()">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M8 3h.01M8 8h.01M8 13h.01" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </button>
            <div class="menu-dropdown">
              <a href="#" class="menu-item" data-action="view">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                  <path d="M1 8s3-6 7-6 7 6 7 6-3 6-7 6-7-6-7-6z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                  <circle cx="8" cy="8" r="2" stroke="currentColor" stroke-width="1.5"/>
                </svg>
                View
              </a>
              <a href="#" class="menu-item" data-action="export">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                  <path d="M8 11V3m0 0L5 6m3-3l3 3m5 2v5a1 1 0 01-1 1H1a1 1 0 01-1-1V8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                Export
              </a>
              <button class="menu-item delete" data-action="delete">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                  <path d="M2 4h12M5 4V2.5A1.5 1.5 0 016.5 1h3A1.5 1.5 0 0111 2.5V4m2 0v9.5a1.5 1.5 0 01-1.5 1.5h-7A1.5 1.5 0 013 13.5V4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                Delete
              </button>
            </div>
          </div>
        </div>
        
        <div class="recording-stats">
          <div class="stat-item">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M8 2v6l4 2m4-2A8 8 0 110 8a8 8 0 0116 0z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            ${this.formatDuration(recording.startTime, recording.endTime)}
          </div>
          <div class="stat-item">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M1 3h14M5 7h10M1 11h14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            ${recording.steps.length} steps
          </div>
        </div>
        
        <div class="recording-preview">
          ${recording.steps.slice(0, 3).map((step, index) => `
            <div class="preview-step">
              <span class="preview-step-number">${index + 1}</span>
              <span>${step.action}</span>
            </div>
          `).join('')}
          ${recording.steps.length > 3 ? `<div class="preview-step">+${recording.steps.length - 3} more</div>` : ''}
        </div>
        
        <div class="recording-footer">
          <span>${this.formatDate(recording.startTime)}</span>
        </div>
      </div>
    `).join('');
    
    // 绑定事件
    this.bindCardEvents();
  }
  
  bindCardEvents() {
    // 卡片点击
    document.querySelectorAll('.recording-card').forEach(card => {
      card.addEventListener('click', () => {
        const id = card.dataset.id;
        this.viewRecording(id);
      });
    });
    
    // 菜单按钮
    document.querySelectorAll('.menu-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const dropdown = btn.nextElementSibling;
        
        // 关闭其他菜单
        document.querySelectorAll('.menu-dropdown').forEach(menu => {
          if (menu !== dropdown) {
            menu.classList.remove('show');
          }
        });
        
        dropdown.classList.toggle('show');
      });
    });
    
    // 菜单项
    document.querySelectorAll('.menu-item').forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        
        const action = item.dataset.action;
        const card = item.closest('.recording-card');
        const id = card.dataset.id;
        
        switch (action) {
          case 'view':
            this.viewRecording(id);
            break;
          case 'export':
            this.exportRecording(id);
            break;
          case 'delete':
            this.showDeleteModal(id);
            break;
        }
        
        // 关闭菜单
        item.closest('.menu-dropdown').classList.remove('show');
      });
    });
  }
  
  viewRecording(id) {
    chrome.tabs.create({
      url: chrome.runtime.getURL(`src/viewer/viewer.html?id=${id}`)
    });
  }
  
  async exportRecording(id) {
    const recording = this.recordings.find(r => r.id === id);
    if (!recording) return;
    
    try {
      await chrome.runtime.sendMessage({
        action: 'EXPORT_RECORDING',
        recording: recording,
        format: 'markdown',
        download: true
      });
      
      this.showNotification('Recording exported successfully', 'success');
    } catch (error) {
      console.error('Failed to export recording:', error);
      this.showNotification('Failed to export recording', 'error');
    }
  }
  
  showDeleteModal(id) {
    this.deleteTargetId = id;
    this.elements.deleteModal.classList.add('show');
  }
  
  hideDeleteModal() {
    this.deleteTargetId = null;
    this.elements.deleteModal.classList.remove('show');
  }
  
  async confirmDelete() {
    if (!this.deleteTargetId) return;
    
    try {
      await chrome.runtime.sendMessage({
        action: 'DELETE_RECORDING',
        recordingId: this.deleteTargetId
      });
      
      // 从本地数组中移除
      this.recordings = this.recordings.filter(r => r.id !== this.deleteTargetId);
      this.filteredRecordings = this.filteredRecordings.filter(r => r.id !== this.deleteTargetId);
      
      this.hideDeleteModal();
      this.renderRecordings();
      
      this.showNotification('Recording deleted successfully', 'success');
    } catch (error) {
      console.error('Failed to delete recording:', error);
      this.showNotification('Failed to delete recording', 'error');
    }
  }
  
  formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    // 如果是今天
    if (diff < 86400000 && date.getDate() === now.getDate()) {
      return `Today at ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
    }
    
    // 如果是昨天
    if (diff < 172800000 && date.getDate() === now.getDate() - 1) {
      return `Yesterday at ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
    }
    
    // 其他情况
    return date.toLocaleDateString([], { 
      year: 'numeric', 
      month: 'short', 
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }
  
  formatDuration(startTime, endTime) {
    if (!startTime || !endTime) return 'N/A';
    
    const start = new Date(startTime);
    const end = new Date(endTime);
    const diff = end - start;
    
    const minutes = Math.floor(diff / 60000);
    const seconds = Math.floor((diff % 60000) / 1000);
    
    if (minutes > 0) {
      return `${minutes}m ${seconds}s`;
    } else {
      return `${seconds}s`;
    }
  }
  
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
  
  showError() {
    this.elements.recordingsGrid.innerHTML = `
      <div class="empty-state">
        <svg width="80" height="80" viewBox="0 0 80 80" fill="none">
          <circle cx="40" cy="40" r="30" stroke="currentColor" stroke-width="2"/>
          <path d="M40 28v16M40 48h.01" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
        </svg>
        <h2>Failed to load recordings</h2>
        <p>Please try refreshing the page</p>
      </div>
    `;
  }
  
  showNotification(message, type) {
    const notification = document.createElement('div');
    notification.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 16px 24px;
      background: ${type === 'success' ? '#10b981' : '#ef4444'};
      color: white;
      border-radius: 8px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
      z-index: 1000;
      animation: slideIn 0.3s ease;
    `;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
      notification.style.animation = 'slideOut 0.3s ease';
      setTimeout(() => notification.remove(), 300);
    }, 3000);
  }
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
  @keyframes slideIn {
    from {
      transform: translateX(100%);
      opacity: 0;
    }
    to {
      transform: translateX(0);
      opacity: 1;
    }
  }
  
  @keyframes slideOut {
    from {
      transform: translateX(0);
      opacity: 1;
    }
    to {
      transform: translateX(100%);
      opacity: 0;
    }
  }
`;
document.head.appendChild(style);

// 初始化管理器
document.addEventListener('DOMContentLoaded', () => {
  new RecordingManager();
});
